import { Service } from "@/middleware/response";
import { getPageList } from "@/utils/db";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { getCaptcha } from "@/utils";
import { AdminUserModel } from "@/models/admin/User";

export const captchaService: Service = (req, res) => {
    const currentCaptcha = getCaptcha();
    req.session.adminLoginCaptcha = currentCaptcha.text;
    res.type("image/svg+xml");
    res.send(currentCaptcha.data);
};

export const loginService: Service = async (req, res) => {
    const { username, password, captcha } = req.body;
    if ([captcha, username, password].some(item => !item)) return res.sendResponse!(400, null, "参数错误");
    if (captcha.toString().toLowerCase() !== req.session.adminLoginCaptcha?.toLocaleLowerCase()) return res.sendResponse!(400, null, "验证码错误");
    const user = await AdminUserModel.findOne({ $or: [{ username }, { email: username }] });
    if (!user) return res.sendResponse!(400, null, "用户名不存在");
    if (!user.status) return res.sendResponse!(400, null, "账号已禁用，请联系管理员");
    const checkPassword = await bcrypt.compare(password, user.password);
    if (!checkPassword) return res.sendResponse!(400, null, "密码错误");
    const { ADMINJWTSECRET, ADMINJWTEXPIREDIN } = process.env;
    const token = jwt.sign({ _id: user._id.toString() }, ADMINJWTSECRET!, { expiresIn: ADMINJWTEXPIREDIN });
    const userObject: { password?: string } & Record<string, any> = user.toObject();
    delete userObject.password;
    res.sendResponse!(200, { user: userObject, token }, "登录成功");
};

export const addUserService: Service = async (req, res) => {
    // roles、remark、status非必填
    const { username, email, password, nickname, avatar } = req.body;
    if ([username, email, password, nickname, avatar].some(item => !item)) return res.sendResponse!(400, null, "参数错误");
    await AdminUserModel.create(req.body);
    res.sendResponse!(200, null, "添加成功");
};

export const getUserListService: Service = async (req, res) => {
    const { page, pageSize } = req.query;
    const pageRes = getPageList({ model: AdminUserModel, params: { page: page as string, pageSize: pageSize as string, $project: { password: 0 } } });
    res.sendResponse!(200, pageRes);
};

export const getUserService: Service = async (req, res) => {
    // token在中间件已做过校验，故在此不需要校验
    const token = req.headers.authorization?.split(`Bearer `)[1] as string;
    const { _id } = jwt.decode(token) as { _id: string };
    const user = await AdminUserModel.findOne({ _id }, { password: 0 });
    res.sendResponse!(200, user);
};

export const updateUserService: Service = async (req, res) => {
    const userParams = req.body;
    if (!userParams) return res.sendResponse!(400, null, "请传入参数");
    delete userParams.password;
    delete userParams.status;
    await AdminUserModel.updateOne({ _id: req.session.user?._id }, userParams);
    res.sendResponse!(200, null, "更新成功");
};

export const logoutService: Service = async (req, res) => {
    delete req.session.adminLoginCaptcha;
    delete req.session.user;
    delete req.session.roles;
    delete req.session.permissions;
    res.sendResponse!(200, null, "退出登录成功");
};
